package com.chris.webservice.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * properties文件的操作工具类
 *
 * @author <a href="mailto:maxid@qq.com">ZengJun</a>
 * @version $$Revision: 13958 $$
 */
public class PropertiesUtil extends Properties {

    protected static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
    /**
     * 只能读取本包
     */
    private static final String DEFAULT_CONFIG_FILE = "META-INF/application.properties";
    private static PropertiesUtil instance = null;

    /**
     * 获得取PropertiesUtil实例
     *
     * @return
     */
    public static PropertiesUtil getInstance() {
        if (instance == null) {
            instance = PropertiesUtil.getInstance(DEFAULT_CONFIG_FILE);
        }
        return instance;
    }

    /**
     * 获得取PropertiesUtil实例
     *
     * @param configFile properties 文件位置
     * @return
     */
    public static PropertiesUtil getInstance(String configFile) {
        InputStream inputStream = null;
        if (configFile != null && configFile.length() > 0) {
            if (configFile.toLowerCase().startsWith("classpath:")) {
                String path = configFile.substring("classpath:".length());
                if (!path.startsWith("/")) {
                    path = "/" + path;
                }
                inputStream = PropertiesUtil.class.getResourceAsStream(path);
            } else {
                if (!configFile.startsWith("/")) {
                    configFile = "/" + configFile;
                }
                inputStream = PropertiesUtil.class.getResourceAsStream(configFile);
            }
        }
        PropertiesUtil propertiesUtil = getInstance(inputStream);
        return propertiesUtil;
    }

    /**
     * 获得取PropertiesUtil实例，适用于读取Jar包内的资源文件
     *
     * @param stream 流形式的属性文件
     * @return
     * @since 2011.10.14
     */
    public static PropertiesUtil getInstance(InputStream stream) {
        PropertiesUtil propertiesUtil = new PropertiesUtil();
        if (stream != null) {
            try {
                propertiesUtil.load(stream);
            } catch (IOException e) {
                logger.error(e.getMessage());
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                    }
                }
            }
        }
        return propertiesUtil;
    }

    /**
     * 读取属性
     *
     * @param param 属性名称
     * @return 属性值
     */
    public String getValue(String param) {
        String result = this.getProperty(param);
        return result == null ? "" : result;
    }
}
